import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:landlore/customWidget/iosStyleCalendar.dart';
import 'package:landlore/model/orderVO.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mccounting_text/mccounting_text.dart';

import '../consts.dart';

class RecordBody extends StatelessWidget {
  final OrderVO orderVO;
  final bool forceChangeState;
  Function? callback;
  List<TextEditingController>? cList;

  RecordBody(
      {super.key,
      required this.orderVO,
      required this.forceChangeState,
      this.cList,
      this.callback}) {
    cList ??= [];
  }

  @override
  Widget build(BuildContext context) {
    bool titleOverFlow = (orderVO.roomNum!.length >= 6) ? true : false;

    // int tempEleAmount =
    //     orderVO.electricityAmount! - orderVO.electricityAmountLastMonth!;
    // int tempWaterAmount = orderVO.waterAmount! - orderVO.waterAmountLastMonth!;
    //
    // //处理使用量为负数的情况
    // //只有订单状态不是已出单的情况,才需要处理,否则直接显示数据库的结果
    // if (orderVO.state != OrderState.BILL_OUT) {
    //   if (tempEleAmount < 0) {
    //     if (Consts.NEGATIVE_BILL_CALCULATE_WAY) {
    //       tempEleAmount = 0;
    //       orderVO.electricityCharge = 0;
    //       //记录最终计算结果
    //       orderVO.electricityAmountResult = 0;
    //     } else {
    //       tempEleAmount = Consts().calculateBillFulSituation(
    //           orderVO.electricityAmountLastMonth!, orderVO.electricityAmount!);
    //       orderVO.electricityCharge =
    //           tempEleAmount * orderVO.electricityUnitPrice!;
    //
    //       orderVO.electricityAmountResult = tempEleAmount;
    //     }
    //   }
    //   if (tempWaterAmount < 0) {
    //     if (Consts.NEGATIVE_BILL_CALCULATE_WAY) {
    //       tempWaterAmount = 0;
    //       orderVO.waterCharge = 0;
    //       orderVO.waterAmountResult = 0;
    //     } else {
    //       tempWaterAmount = Consts().calculateBillFulSituation(
    //           orderVO.waterAmountLastMonth!, orderVO.waterAmount!);
    //       orderVO.waterCharge = tempWaterAmount * orderVO.waterUnitPrice!;
    //       orderVO.waterAmountResult = tempWaterAmount;
    //     }
    //   }
    // }

    return Container(
      padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 20.h),
      color: Colors.grey,
      child: orderVO.state == null || orderVO.state == 0
          ? Text(
              '暂无可以信息',
              style: TextStyle(
                  fontFamily: '欢字卡通手书', fontSize: 50.sp, color: Colors.black),
            )
          : SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white70,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(30.r),
                          topRight: Radius.circular(30.r)),
                    ),
                    padding:
                        EdgeInsets.only(left: 20.w, right: 10.w, top: 10.h),
                    child: Row(
                      children: [
                        Expanded(
                            flex: 2,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  orderVO.roomNum!,
                                  style: Consts.titleText.copyWith(
                                      fontSize: titleOverFlow ? 45.sp : 65.sp),
                                ),
                                Text(
                                  orderVO.contact == null
                                      ? ''
                                      : orderVO.contact!,
                                  style: Consts.titleText.copyWith(
                                      fontSize: 25.sp,
                                      fontWeight: FontWeight.w600,
                                      fontFamily: '欢字卡通手书'),
                                ),
                              ],
                            )),
                        Expanded(
                            flex: 1,
                            child: IosStyleCalendar(
                                year: orderVO.createDate!.year,
                                month: orderVO.createDate!.month))
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white70,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '合计:',
                          style:
                              TextStyle(fontSize: 65.sp, fontFamily: '欢字卡通手书'),
                        ),
                        Expanded(
                          child: Center(
                            child: McCountingText(
                              begin: 0,
                              end: double.parse(getSum(orderVO)),
                              precision: 1,
                              style: TextStyle(
                                  fontSize: 60.sp, fontFamily: '欢字卡通手书'),
                              duration: const Duration(seconds: 1),
                              curve: Curves.fastOutSlowIn,
                            ),
                            // Text(
                            //   '${getSum(orderVO)}',
                            //   overflow: TextOverflow.visible,
                            //   style: TextStyle(fontSize: 60.sp),
                            // ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const Divider(
                    thickness: 5,
                    color: Colors.black,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: const Color(0xff6c757d),
                        image: DecorationImage(
                            image:
                                const AssetImage('assets/images/crossword.png'),
                            repeat: ImageRepeat.repeat,
                            colorFilter: ColorFilter.mode(
                                Colors.black.withOpacity(0.8),
                                BlendMode.srcIn)),
                        borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(30.r),
                            bottomRight: Radius.circular(30.r))),
                    padding: EdgeInsets.only(left: 10.w, right: 10.w),
                    child: Column(
                      children: [
                        Center(
                          child: Text(
                            '下月部分',
                            style: TextStyle(
                                decoration: TextDecoration.none,
                                fontSize: 25.sp,
                                fontFamily: "欢字卡通手书",
                                color: Colors.black87),
                          ),
                        ),
                        itemWidget(
                          title: '租金',
                          price: orderVO.rent!.toStringAsFixed(0),
                          forceChangeState: forceChangeState,
                          controller: cList!.isEmpty ? null : cList![0],
                          callback: (value) {
                            orderVO.rent = double.parse(value);
                            callback(orderVO) {}
                          },
                        ),
                        itemWidget(
                          title: '附加费',
                          price: orderVO.otherCharge!.toStringAsFixed(0),
                          forceChangeState: forceChangeState,
                          controller: cList!.isEmpty ? null : cList![1],
                          callback: (value) {
                            orderVO.otherCharge = double.parse(value);
                          },
                        ),
                        Center(
                          child: Text(
                            '本月部分',
                            style: TextStyle(
                                decoration: TextDecoration.none,
                                fontSize: 25.sp,
                                fontFamily: "欢字卡通手书",
                                color: Colors.black87),
                          ),
                        ),
                        itemWidget(
                            title: '用电量',
                            price:
                                '${orderVO.electricityAmount!.toStringAsFixed(0)} - ${orderVO.electricityAmountLastMonth!.toStringAsFixed(0)} = ${orderVO.electricityAmountResult!.toStringAsFixed(0)}',
                            forceChangeState: forceChangeState,
                            controller: cList!.isEmpty ? null : cList![2],
                            callback: (value) {
                              orderVO.electricityAmountResult =
                                  int.parse(value);
                            },
                            intOnly: true,
                            type: 1),
                        itemWidget(
                          title: '电费',
                          price:
                              (orderVO.electricityCharge!).toStringAsFixed(1),
                          forceChangeState: forceChangeState,
                          controller: cList!.isEmpty ? null : cList![3],
                          callback: (value) {
                            orderVO.electricityCharge = double.parse(value);
                          },
                        ),
                        itemWidget(
                            title: '用水量',
                            price:
                                '${orderVO.waterAmount!.toStringAsFixed(0)} - ${orderVO.waterAmountLastMonth!.toStringAsFixed(0)} = ${orderVO.waterAmountResult!.toStringAsFixed(0)}',
                            forceChangeState: forceChangeState,
                            controller: cList!.isEmpty ? null : cList![4],
                            callback: (value) {
                              orderVO.waterAmountResult = int.parse(value);
                            },
                            intOnly: true,
                            type: 2),
                        itemWidget(
                          title: '水费',
                          price: (orderVO.waterCharge!).toStringAsFixed(1),
                          forceChangeState: forceChangeState,
                          controller: cList!.isEmpty ? null : cList![5],
                          callback: (value) {
                            orderVO.waterCharge = double.parse(value);
                          },
                        ),

                        //电表照片
                        orderVO.eleImage == null
                            ? const SizedBox()
                            : GestureDetector(
                                onTap: () async {
                                  await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => FullScreenImage(
                                              imagePath: orderVO.eleImage!)));
                                },
                                child: Hero(
                                  tag: '${orderVO.eleImage}',
                                  child: Container(
                                      margin: EdgeInsets.all(10.h),
                                      decoration: BoxDecoration(
                                          color: Colors.black54,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20.r))),
                                      width: 350.w,
                                      height: 350.w,
                                      child: ClipRRect(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20.r)),
                                          child: ThumbnailImage(
                                              imagePath: orderVO.eleImage!))
                                      // Image.file(File(orderVO.eleImage!),
                                      //     fit: BoxFit.fitWidth),
                                      ),
                                ),
                              ),

                        //水表照片
                        orderVO.waterImage == null
                            ? const SizedBox()
                            : GestureDetector(
                                onTap: () async {
                                  await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => FullScreenImage(
                                              imagePath: orderVO.waterImage!)));
                                },
                                child: Hero(
                                  tag: '${orderVO.waterImage}',
                                  child: Container(
                                      margin: EdgeInsets.all(10.h),
                                      decoration: BoxDecoration(
                                          color: Colors.black54,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20.r))),
                                      width: 350.w,
                                      height: 350.w,
                                      child: ClipRRect(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20.r)),
                                          child: ThumbnailImage(
                                              imagePath: orderVO.waterImage!))
                                      // Image.file(File(orderVO.waterImage!),
                                      //     fit: BoxFit.fill),
                                      ),
                                ),
                              ),
                        SizedBox(
                          height: 20.h,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 10.h,
                  )
                ],
              ),
            ),
    );
  }

  getSum(OrderVO orderVO) {
    return (orderVO.rent! +
            orderVO.otherCharge! +
            orderVO.electricityCharge! +
            orderVO.waterCharge!)
        .toStringAsFixed(1);
  }
}

class itemWidget extends StatelessWidget {
  final String title;
  final String price;
  final bool forceChangeState;
  final Function callback;
  TextEditingController? controller;
  bool? intOnly;

  //用于标记区分 1:用电量/2:用水量/0:其他 三个类别
  int? type;

  itemWidget({
    super.key,
    required this.title,
    required this.price,
    required this.forceChangeState,
    required this.callback,
    this.controller,
    this.intOnly,
    this.type,
  }) {
    intOnly ??= false;
    type ??= 0;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 10.h),
      height: 40.h,
      decoration: BoxDecoration(
          color: const Color(0xff6c757d),
          image: DecorationImage(
              image: const AssetImage('assets/images/crossword.png'),
              repeat: ImageRepeat.repeat,
              colorFilter: ColorFilter.mode(
                  Colors.black.withOpacity(0.8), BlendMode.srcIn))),
      child: Stack(
        children: [
          Positioned(
              left: 70.w,
              top: 14.h,
              child: Text(
                '・・・・・・・・・・・・・・・・・・・・・・・・・・・・・',
                style: TextStyle(fontSize: 10.sp),
              )),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                title,
                style: TextStyle(
                    decoration: TextDecoration.none,
                    fontSize: 30.sp,
                    fontFamily: "欢字卡通手书",
                    color: Colors.black87),
              ),
              SizedBox(
                child: !forceChangeState
                    ? Container(
                        decoration: BoxDecoration(
                            color: const Color(0xff6c757d),
                            image: DecorationImage(
                                image: const AssetImage(
                                    'assets/images/crossword.png'),
                                repeat: ImageRepeat.repeat,
                                colorFilter: ColorFilter.mode(
                                    Colors.black.withOpacity(0.8),
                                    BlendMode.srcIn))),
                        child: Text(
                          type == 0
                              ? price
                              : type == 1
                                  ? '$price度'
                                  : '$price吨',
                          style: TextStyle(
                              decoration: TextDecoration.none,
                              fontSize: 30.sp,
                              fontFamily: "欢字卡通手书",
                              color: Colors.black87),
                        ),
                      )
                    : Container(
                        width: 150.w,
                        color: Colors.white,
                        child: TextField(
                          keyboardType: const TextInputType.numberWithOptions(
                              decimal: true, signed: true),
                          inputFormatters: intOnly!
                              ? [
                                  FilteringTextInputFormatter.allow(
                                      RegExp(r'^-?\d*')),
                                ]
                              : [
                                  FilteringTextInputFormatter.allow(
                                      RegExp(r'^\d*\.?\d*|-?\d*\.?\d*')),
                                ],
                          controller: controller,
                          onChanged: (value) {
                            if (value == '') {
                              value = '0';
                            }
                            callback(value);
                          },
                          // decoration: InputDecoration(
                          //   labelText: title,
                          //   labelStyle:
                          //       TextStyle(color: Colors.black, fontSize: 40.sp),
                          //   floatingLabelStyle:
                          //       const TextStyle(color: Color(0xff45C7B8)),
                          //   suffixText: unit,
                          // ),
                          style: TextStyle(fontSize: 30.sp),
                        ),
                      ),
              )
            ],
          )
        ],
      ),
    );
  }
}

class FullScreenImage extends StatefulWidget {
  final String imagePath;

  const FullScreenImage({super.key, required this.imagePath});

  @override
  State<FullScreenImage> createState() => _FullScreenImageState();
}

class _FullScreenImageState extends State<FullScreenImage> {
  double scale = 1;
  double previousScale = 1;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pop(context);
      },
      onScaleStart: (details) {
        previousScale = scale;
      },
      onScaleUpdate: (details) {
        setState(() {
          scale = previousScale * details.scale;
        });
      },
      child: Container(
        color: Colors.black,
        alignment: Alignment.center,
        child: Hero(
          tag: widget.imagePath,
          child: Transform.scale(
            scale: scale,
            child: Image.file(
              File(widget.imagePath),
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),
    );
  }
}

class ThumbnailImage extends StatelessWidget {
  final String imagePath;

  ThumbnailImage({required this.imagePath});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<ImageInfo>(
      future: getImageInfo(imagePath),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final imageInfo = snapshot.data!;
          final double aspectRatio = imageInfo.image.width.toDouble() /
              imageInfo.image.height.toDouble();

          // 根据图片宽高比例判断图片方向
          if (aspectRatio >= 1.0) {
            // 横屏图片
            return AspectRatio(
              aspectRatio: aspectRatio,
              child: Image.file(
                File(imagePath),
                fit: BoxFit.fitWidth, // 适应宽度
              ),
            );
          } else {
            // 竖屏图片
            return AspectRatio(
              aspectRatio: aspectRatio,
              child: Image.file(
                File(imagePath),
                fit: BoxFit.fitHeight, // 适应高度
              ),
            );
          }
        } else {
          return CircularProgressIndicator(); // 显示加载指示器
        }
      },
    );
  }

  Future<ImageInfo> getImageInfo(String imagePath) async {
    final completer = Completer<ImageInfo>();
    final image = Image.file(
      File(imagePath),
      fit: BoxFit.cover,
    );
    image.image.resolve(ImageConfiguration()).addListener(
      ImageStreamListener(
        (info, synchronousCall) {
          completer.complete(info);
        },
      ),
    );
    return completer.future;
  }
}
